package com.lagou.servlet;


import com.lagou.bena.Student;
import com.lagou.service.AdminServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


@WebServlet(name = "addStuServlet", urlPatterns = "/addStu")
public class addStuServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Student stu = new Student();
        AdminServiceImp asi = new AdminServiceImp();
        // 设置编码格式为uft-8
        request.setCharacterEncoding("utf-8");
        // 将从前端页面获取到的值，分别set到Student对象中，得到Student对象
        stu.setStuName(request.getParameter("stuName"));
        stu.setSex(request.getParameter("sex"));
        stu.setBirthday(request.getParameter("birthday"));
        stu.setEmail(request.getParameter("email"));
        stu.setInfo(request.getParameter("info"));
        // 获取数据库执行添加操作的返回值
        int i = asi.addStuService(stu);
        if (i > 0) {
            // 添加学生信息成功，跳转到学生列表
            // 查询所有学生信息，得到list集合
            List<Student> students = asi.showAllService();

            // 将查询出的所有学生信息集合存入session对象中实现多个请求共享
            request.getSession().setAttribute("students", students);
            request.getSession().setAttribute("addRes", "success");

            // 实现客户端的跳转
            response.sendRedirect("stuList.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
